package com.jia.service.impl;

import com.jia.pojo.SysRole;
import com.jia.pojo.SysUser;
import com.jia.service.MyService;
import com.jia.service.RoleMapperService;
import com.jia.service.UserMapperService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.Pbkdf2PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class MyerviceImpl implements MyService {
    @Autowired
    private UserMapperService userMapperService;
    @Autowired
    private RoleMapperService roleMapperService;
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        //实现dao相关业务
        SysUser byName = userMapperService.findByName(s);
        if (byName == null){
            System.out.println("用户不存在");
            return null;
        }
        else {
            List<SysRole> roles = roleMapperService.findByUid(byName.getId());
            List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
            if(roles != null && roles.size()>0){
                for (SysRole role : roles) {
                    String roleName = role.getRoleName();
                    authorities.add(new SimpleGrantedAuthority(roleName));
                }
            }
            return new User(byName.getUsername(),new Pbkdf2PasswordEncoder("ahead").encode(byName.getPassword()),authorities);
        }

    }
}
